# encoding=utf-8

import os
import re
import time
import projectConfig
adbRebootCommand = "adb -s %s reboot"

pullCommand = "adb -s %s pull /sdcard/espresso %s"

adbPushConfig = 'adb -s %s push config/%s /sdcard/espressoConfig/config.xml'
pushRtxt = "adb -s %s push %s /sdcard/espressoConfig/%s"

removeFolderCommand = "adb -s %s shell rm -rf %s"

espressoPicPath = '/sdcard/espresso'

pullAnrLogCommand = "adb -s %s pull /data/anr %s"
zipCommand = "tar -zcvf %s %s"

mkdirCommand = "adb -s %s shell mkdir -p /sdcard/espresso/"

# 清除device日志缓存
clearLogcatCammand = "adb -s %s shell logcat -c"
clearMainLogcatCommand = "adb -s %s shell logcat -b main -c"
clearSystemLogcatCommand = "adb -s %s shell logcat -b system -c"


def restart_adb():
    retry = 3
    while retry > 0:
        os.popen("adb kill-server").read()
        time.sleep(1)
        if 'successfully' in os.popen("adb start-server").read():
            return True
        retry -= 1
    else:
        return False


def checkCellOnline():

    devices = re.findall(r"(\S+)\s*device\n", os.popen('adb devices').read())
    return devices

def checkCellOnlineIos():
    devices = re.findall("\[([a-zA-Z0-9]+)\]\n", os.popen('instruments -s devices').read())
    return devices

def pushConfigToDevice(device, config):
    if projectConfig.pushConfigFile:
        print(os.popen(adbPushConfig % (device, config)).read())


# 清系统日志缓存
def clearDeviceLogCache(device):
    os.popen(clearMainLogcatCommand % device)
    os.popen(clearSystemLogcatCommand % device)
    os.popen(clearLogcatCammand % device)




# 删除手机里某个文件夹
def deleteDeviceFolder(device, folder):
    os.popen(removeFolderCommand % (device, folder))



# 强制停止app
def forceStopApp(device):
    stopCommand = "adb -s %s shell am force-stop " + projectConfig.clientPackage
    os.popen(stopCommand % device)


# 强制停止app
def stopApp(device, packageName):
    stopCommand = 'adb -s %s shell am force-stop %s' % (device, packageName)
    os.popen(stopCommand)


if __name__ == '__main__':
    # resultPath = os.path.join('share', '2001')
    device = '6d407e2b'
    # testRunner = getTestRunner(device)
    # pic('14dc2c34', '1')
    # mkdir(device)
